<?php
	// -----------   Page Vars    ----------
	$to_root = '';
	$authorized = array(0, 1);

	$menu_selected = 2;
	
	//  ---- init
	include($to_root.'_classes/init.php');
	
	$main = new ViewDescriptor('main');
	Template::addBreadcrumb('home.php', 'Home');
	
	/* ========   INSERT CODE HERE   ======== */
	//=====================================================================================        POST
	if(isset($_POST['action']) && $_POST['action']=='new' &&  							//---------------  NEW TO-DO
		isset($_POST['title'])&&
		isset($_POST['text']) && 
		isset($_POST['tD']) && 
		isset($_POST['p_id'])){
	
		$p_id = $_POST['p_id'];
			
		$title = ($_POST['title']);
		$text = ($_POST['text']);
		$tD = ($_POST['tD']);
		$pH = (isset($_POST['pH'])) ? ($_POST['pH']) : 0;
		
		$newid = $GLOBALS['Db-I']->newTodo($p_id, $title, $text, $tD, $pH);

		if(!is_array($newid)){
			if(isset($_POST['lID'])) header('Location: projects.php?lId='.$p_id.'&msg=insert_success');
			else header('Location: projects.php?id='.$p_id.'&msg=insert_success');
		} else {
			if(isset($newid['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
				header('Location: todos.php?msg=not_authorized');
			} else {
				header('Location: todos.php?msg=update_error');
			}
		}
	} else if(isset($_POST['action']) && $_POST['action']=='edit' &&  					//---------------  EDIT TO-DO
		isset($_POST['title'])&&
		isset($_POST['text']) && 
		isset($_POST['tD']) && 
		isset($_POST['id']) && 
		isset($_POST['status'])){

		$title = ($_POST['title']);
		$text = ($_POST['text']);
		$tD = ($_POST['tD']);
		$pH = (isset($_POST['pH'])) ? ($_POST['pH']) : 0;
		$id = ($_POST['id']);
		$status = ($_POST['status']);
		
		$idp = isset($_POST['lId']) ? $_POST['lId'] : $_POST['pId'];
		
		$id = $GLOBALS['Db-I']->editTodo($id, $title, $text, $tD, $pH, $status);
		if(!is_array($id)){
			if(isset($_POST['lId'])) header('Location: projects.php?lId='.$idp.'&msg=update_success');
			else if(isset($_POST['pId'])) header('Location: projects.php?id='.$idp.'&msg=update_success');
			else header('Location: todos.php?&msg=update_success');
		} else {
			if(isset($id['Error']) && $id['Error'] == ERROR_NOT_ALLOWED){
				header('Location: todos.php?msg=not_authorized');
			} else {
				header('Location: todos.php?msg=update_error');
			}
		}
	} else if(isset($_GET['action']) && $_GET['action']=='delete' &&  					//---------------  DELETE TO-DO
		isset($_GET['id'])){ 
		$id = $_GET['id'];
		
		
		$newid = $GLOBALS['Db-I']->deleteTodo($id);
		if(!is_array($newid)){
			if(isset($_GET['lId'])) header('Location: projects.php?&lId='.$_GET['lId'].'&msg=delete_success');
			else if(isset($_GET['pId'])) header('Location: projects.php?id='.$_GET['pId'].'&msg=delete_success');
			else header('Location: todos.php?&msg=delete_success');
		} else {
			if(isset($newid['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
				header('Location: todos.php?msg=not_authorized');
			} else {
				header('Location: todos.php?msg=delete_error');
			}
		}	
	} else if(isset($_GET['action']) && $_GET['action']=='unlink' &&  					//---------------  UNLINK PROJECT
		isset($_GET['tId']) && isset($_GET['lId'])){ 
	
		$newid = $GLOBALS['Db-I']->removeTodoFromList($_GET['lId'], $_GET['tId']);
		if(!is_array($newid)){
			header('Location: todos.php?msg=delete_success');
		} else {
			if(isset($newid['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
				header('Location: todos.php?msg=not_authorized');
			} else {
				header('Location: todos.php?msg=delete_error');
			}
		}	
	} else if(isset($_GET['action']) && $_GET['action']=='unlink' &&  					//---------------  UNLINK User 
		isset($_GET['tId']) && isset($_GET['uId'])){ 
	
		$newid = $GLOBALS['Db-I']->removeUserFromTodo($_GET['tId'], $_GET['uId']);
		print_r($newid);
		if(!is_array($newid)){
			header('Location: '.$_SERVER['HTTP_REFERER'].'&msg=delete_success');
		} else {
			if(isset($newid['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
				header('Location: todos.php?msg=not_authorized');
			} else {
				header('Location: todos.php?msg=delete_error');
			}
		}	
	}
	
	$p_id = (isset($_GET['pId'])) ? $_GET['pId'] : -1;
	$p_id = (isset($_GET['lId'])) ? $_GET['lId'] : $p_id;
	$list = ($p_id != -1) ?  $GLOBALS['Db-I']->getProject($p_id) : -1;
	
	//=====================================================================================       View
	if(isset($_GET['id']) && $_GET['id']!= '' && !isset($_GET['action'])){  								// ----------------------------------- view Todo
		if(isset($_GET['pId'])) { //--------- Breadcrumbs for Project or Todo (depends on Referrer)
			Template::addBreadcrumb('projects.php', 'Projekte');
			Template::addBreadcrumb('projects.php?id='.$_GET['pId'], Template::cutString($list->getTitle(), 20));		
		} else if(isset($_GET['lId'])) {
			Template::addBreadcrumb('todos.php', 'Todos');
			Template::addBreadcrumb('projects.php?lId='.$_GET['lId'], Template::cutString($list->getTitle(), 20));		
		} else Template::addBreadcrumb('todos.php', 'Todos');
		
		$content = new ViewDescriptor('content/todos_view');
		$todo = $GLOBALS['Db-I']->getTodo(($_GET['id']), true); //mit linkedLists =true
		
		$public = (isset($_GET['pId'])) ? '&amp;pId='.$_GET['pId'] : 
				((isset($_GET['lId'])) ? '&amp;lId='.$_GET['lId'] : '');
		
		if($_SESSION['User']['id'] == $todo->getCreator()->getId() || $_SESSION['User']['group']=='admin'){
			$a = new SubViewDescriptor('authorized');
			$a2 = new SubViewDescriptor('authorized2');
			$a->addValue('id', $todo->getId());
			$content->addSubView($a);
			$content->addSubView($a2);
		} else {
			$content->removeSubView('authorized');
			$content->removeSubView('authorized2');
		}
		
		$u = $todo->getUsers();
	//print_r($u);
		if(count($u)>0){
			foreach($u as $p){
				if(!(is_array($p) && !isset($p['Error']))){
					$p_s = new SubViewDescriptor('user');
					
				
					
					if($todo->getCreator()->getId() == $p->getId()){
						$p_s->removeSubView('ersteller');
						$p_s->addValue('extra', '(Ersteller)');
					} else {
						//ersteller adden
						$uu = new SubViewDescriptor('ersteller');
						$uu->addValue('id', $p->getId());
						$uu->addValue('tId', $todo->getId());
						$p_s->addSubView($uu);
						unset($uu);
						$p_s->addValue('extra', '');
					}
					$p_s->addValue('id', $p->getId());
					$p_s->addValue('name', $p->getName());
					$p_s->addValue('tId', $todo->getId());
					$content->addSubView($p_s);
					unset($p_s);
				}
			}
		}
	
		$ps = $todo->getProjects();
		if(count($ps)>0){
			foreach($ps as $p){
				$p_s = new SubViewDescriptor('projects');
				$p_s->addValue('id', $p['id']);
				$p_s->addValue('title', $p['t']);
				$p_s->addValue('tId', $todo->getId());
				$content->addSubView($p_s);
				unset($p_s);
			}
		}else $content->removeSubView('projects');
		
		$allmessages = -1;
		
		$msgs = $GLOBALS['Db-I']->getMessagesForTodo($todo->getId(), 0, TODO_NEW_MESSAGES_COUNT);
		if($msgs != array()){
			foreach($msgs as $msg){
				$m = new SubViewDescriptor('messages');
				if($allmessages == -1) $allmessages = $msg->getAllMsgCount();
				$m->addValue('id', $msg->getId());
				$m->addValue('tId', $todo->getId());
				$m->addValue('title', $msg->getTitle());
				$m->addValue('date', $msg->getDate());
				$m->addValue('u_id', $msg->getAuthor()->getId());
				$m->addValue('u_name', $msg->getAuthor()->getName());
				$m->addValue('text', Template::cutString($msg->getText(), 140));
				$m->addValue('reply_count', $msg->getReplyCount());
				
				$content->addSubView($m);
				unset($m);
			}
			$content->removeSubView('no_msgs');
		} else {
			$content->removeSubView('messages');
			$nm = new SubViewDescriptor('no_msgs');
			$content->addSubView($nm);
		}
		
		
		Template::addBreadcrumb('todos.php?id='.$todo->getId(), $todo->getTitle());
		$content->addValue('id', $todo->getId());
		$content->addValue('msg_count', (($allmessages==0)||($allmessages==-1)) ? 'Keine': $allmessages);
		$content->addValue('public', $public);
		$content->addValue('title', $todo->getTitle());
		$content->addValue('text', nl2br($todo->getDescription()));
			
	} else if(isset($_GET['action']) && $_GET['action']=='new'){											// ----------------------------------- new Todo
		if(isset($_GET['pId'])) { //--------- Breadcrumbs for Project or Todo (depends on Referrer)
			Template::addBreadcrumb('projects.php', 'Projekte');
			Template::addBreadcrumb('projects.php?id='.$_GET['pId'], Template::cutString($list->getTitle(), 20));		
		} else if(isset($_GET['lId'])) {
			Template::addBreadcrumb('todos.php', 'Todos');
			Template::addBreadcrumb('projects.php?lId='.$_GET['lId'], Template::cutString($list->getTitle(), 20));		
		} else Template::addBreadcrumb('todos.php', 'Todos');

		$content = new ViewDescriptor('content/todos_new');
		$content->addValue('p_id', $p_id);
		if(isset($_GET['lId'])){ //set subview for lId if project should be private
			$l = new SubViewDescriptor('lID');
			$content->addSubView($l);
			unset($l);
		} else $content->removeSubView('lID');
		Template::addBreadcrumb('todo.php?action=new', 'Neues Todo');
		
	} else if(isset($_GET['action']) && $_GET['action']=='edit' && isset($_GET['id']) && $_GET['id'] != ''){// ----------------------------------- edit Todo
		
		if(isset($_GET['pId'])) { //--------- Breadcrumbs for Project or Todo (depends on Referrer)
			Template::addBreadcrumb('projects.php', 'Projekte');
			Template::addBreadcrumb('projects.php?id='.$_GET['pId'], Template::cutString($list->getTitle(), 20));		
		} else if(isset($_GET['lId'])) {
			Template::addBreadcrumb('todos.php', 'Todos');
			Template::addBreadcrumb('projects.php?lId='.$_GET['lId'], Template::cutString($list->getTitle(), 20));		
		} else Template::addBreadcrumb('todos.php', 'Todos');
		
		$action = ($_GET['action']);
		$id = ($_GET['id']);
		$todo = $GLOBALS['Db-I']->getTodo(($_GET['id']));
		
		if(!is_array($todo)){
			$content = new ViewDescriptor('content/todos_edit');
			
			$s = $todo->getStatus(Todo::GET_STATUS_SHORT);
			$content->addValue('status_n', ($s == Todo::STATUS_NEW) ? 'selected="selected"' : '');
			$content->addValue('status_oS', ($s == Todo::STATUS_ON_SCHEDULE) ? 'selected="selected"' : '');
			$content->addValue('status_bS', ($s == Todo::STATUS_BEHIND_SCHEDULE) ? 'selected="selected"' : '');
			$content->addValue('status_w', ($s == Todo::STATUS_WAITING) ? 'selected="selected"' : '');
			$content->addValue('status_c', ($s == Todo::STATUS_COMPLETED) ? 'selected="selected"' : '');
			
			Template::addBreadcrumb('todos.php?id='.$todo->getId(), Template::cutString($todo->getTitle(), 20));
			Template::addBreadcrumb('todos.php?id='.$todo->getId().'&action=edit', 'bearbeiten');
			
			$content->addValue('id', $todo->getId());
			$content->addValue('title', $todo->getTitle());
			$content->addValue('text', $todo->getDescription());
			$content->addValue('date', $todo->getTargetDate());
			$content->addValue('pH', $todo->getProjectedHours());
			$content->addValue('public', (isset($_GET['pId'])) ? 'pId' : 'lId');
			$content->addValue('public_id', (isset($_GET['pId'])) ? $_GET['pId'] :
									((isset($_GET['lId'])) ? $_GET['lId'] : ''));
		}
	} else {																							// ----------------------------------- view all
		Template::addBreadcrumb('todos.php', 'Todos');
		// Get All Todos in all Folders
		$content = new ViewDescriptor('content/todos');
		$content->addValue('p_id', $p_id);
		
		//Pagina
		$perPage = 30;
		$page = (isset($_GET['p'])) ? $_GET['p'] : 1;
		
		// get all private lists
		$proj = $GLOBALS['Db-I']->getProjects($_SESSION['User']['id'], -1, -1, 't', true); // ($uId $from=-1, $rows=-1, sort=title, withoutTodos=true)
		$new = true;
		$firstId = -1;
		$allcount = 0;
		$todoIdArray = array();
		
		
		if(!isset($proj['Error']) && count($proj)>0){
			foreach($proj as &$project){
				$pSV = new SubViewDescriptor('projects');
				
				if($project->getOwner()->getId() != $_SESSION['User']['id']){
					$s = new SubViewDescriptor('shared');
					$pSV->addSubView($s);
				} else $pSV->removeSubView('shared');
				
				$pSV->addValue('id', $project->getId());
				$pSV->addValue('title', $project->getTitle());
				$pSV->addValue('desc', $project->getDescription());
				$pSV->addValue('todo_count', $project->getTodoCount());
				
				$content->addSubView($pSV);
				
				unset($pSV);
				
			}
		} else $content->removeSubView('projects');
	}
	
	/* ========   NORMAL STUFF   ========= */
	// Messages
	if(isset($_GET['msg']) && isset($errors) && is_array($errors) && isset($error_class) && is_array($error_class)){
    	$get_msg = explode('|', $_GET['msg']);
    	foreach($get_msg as $error){
    		if(isset($errors[$error]) && isset($error[$GLOBALS['Localization']['language']])){
    			$GLOBALS['Messages'][] = '<span class="msg_'.$error_class[$error].'">'.$errors[$error].'</span>';
    		}
    	}
    }
    // render Main Template
	Template::generateMenu($main, $menu_selected);
	Template::renderBreadCrumb($main);
	$main->addValue('messages', implode("\n", $GLOBALS['Messages']));
	$main->addValue('content', $content->render());
	$main->addValue('script', '<script type="text/javascript" src="'.$GLOBALS['tpl']['root'].'_template/todolist/'.$GLOBALS['Localization']['language'].'/js/todos.js"></script>');
	$main->addValue('style', '<link rel="stylesheet" href="'.$GLOBALS['tpl']['root'].'_template/todolist/'.$GLOBALS['Localization']['language'].'/css/todo.css" type="text/css"  media="screen"/>');
	
	echo $main->render(); 
?>